<?php
	
	/*
	if (!class_exists('GershImageHelper')) {
		App::import('Helper', 'Extend.GershImage');
	}
	if (!class_exists('LightboxHelper')) {
		App::import('Helper', 'Extend.Lightbox');
	}*/
	

	class EmbedHelper extends AppHelper {

		var $helpers = array('Extend.GershImage', 'Extend.Lightbox');
		var $images = array();
		
		function init() {
			debug("init");
		}
		
		function substituteEmbedTags ($text, $img_array = array()){
			
			$this->images = $img_array;
			$text = preg_replace( "/((\[image:)([^\]]+)\])/eU", '$this->gentag("\\1")', $text);
			return $text;
		}
		
		function gentag($match) {
			//debug($this->images);
			if(preg_match("/image:([0-9]+)\s+size:([a-z]+)/", $match, $matches)) {
				$view =& ClassRegistry::getObject('view');
				//debug($view);
				if(stripos($match, 'lightbox')) {
					$lightbox = 1;
				} else {
					$lightbox = 0;
				}
				if(preg_match("/align:([a-z]+)/", $match, $matches_align)) {
					$align = $matches_align[1];
				} else {
					$align = 0;
				}
				$key = 'embed_image' . $matches[1] . "_" . $matches[2] . "_" . $lightbox . "_" . $align;
				return $view->element('fetch_image', array('plugin'=>'images', 'cache'=> array('key' => $key, 'time' => '+1 day'), 'key'=>'test', 'id'=>$matches[1], 'size'=>$matches[2], 'show_lightbox'=>$lightbox,'align'=>$align), true);
				
				/* Original from the element which fails to load
				$image = $this->requestAction('/images/images/fetch/' . $id); 
				$class= "embed-image embed-" . $size;
				$div_pre = "";
				$div_post = "";
				if(!empty($align) and $align !== false) {
					$div_pre = '<div class="object-' . $align . '">';
					$div_post = "</div>";
				}
				if($show_lightbox === true) {
					return $div_pre . $lightbox->img(null, $image['Image']['dir'] . DS . $image['Image']['filename'], array('title' => $image['Image']['title'], 'class'=>$class), array(), $size) . $div_post;
				} else {
					return $div_pre . $gershImage->resize($image['Image']['dir'] . DS . $image['Image']['filename'], $size, array('title'=>$image['Image']['title'], 'alt'=>$image['Image']['title'], 'class'=>$class)) . $div_post;
				}*/
				
				
				
			} else {
				return '<p class="error">' . __('No image found', true) . '</p>';
			}
			
			//[image:{id} size:{thumb|medium|full|original} lightbox:{true}]  "|(\d{2}/\d{2}/)(\d{4})|U"

		}
		
	}
?>